<?php


namespace app\admin\controller\mall;


use app\admin\model\MallExpress;
use app\admin\model\MallGoods;
use app\admin\model\MallOrder;
use app\api\help\SendMsg;
use app\api\model\AllInPay;
use app\api\model\MallCollage;
use app\api\model\MallTradeRecordLog;
use app\api\model\MallUser;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use jianyan\excel\Excel;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="拼团失败订单")
 */

class OrderStatus40 extends AdminController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        
        $this->model = new \app\admin\model\MallOrder();
        
    }
    /**
     * @NodeAnotation(title="列表")
     */
    public function statusIndex()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            [$page, $limit, $where] = $this->buildTableParames();
            $where[] = ['order_status', '=', 40];
            $where[] = ['ea_mall_order.is_virtual', '=', 0];
            $count   = $this->model
                ->with(['goods', 'user', 'collage'])
                ->where($where)
                ->count();
            $list    = $this->model
                ->with(['goods', 'user', 'collage'])
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data    = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }
    
    /**
     * @NodeAnotation(title="订单详情")
     */
    public function detail($id)
    {
        $row = $this->model->with(['goods', 'user'])->find($id)->toArray();
        empty($row) && $this->error('数据不存在');
        switch ($row[ 'order_status' ]) {
            case 0:
                $row[ 'order_status' ] = '未支付';
                break;
            case 1:
                $row[ 'order_status' ] = '拼团已结束';
                break;
            case 10:
                $row[ 'order_status' ] = '进行中';
                break;
            case 20:
                $row[ 'order_status' ] = '取消';
                break;
            case 30:
                $row[ 'order_status' ] = '拼团成功';
                break;
            case 40:
                $row[ 'order_status' ] = '拼团失败';
                break;
            case 50:
                $row[ 'order_status' ] = '已发货';
                break;
            case 60:
                $row[ 'order_status' ] = '已完成';
                break;
            case 70:
                $row[ 'order_status' ] = '已退款';
                break;
        }
        $row[ 'collage_num' ] = MallCollage::where([['collage_id', '=', $row[ 'collage_id' ]]])->value('collage_num') ?? 0;
        $row[ 'order_num' ]   = MallOrder::where([['u_collage_id', '=', $row[ 'collage_id' ]], ['order_status', 'in', '10,30,50,60']])->count() ?? 0;
        $row[ 'order_user' ]  = [];
        if ($row[ 'order_num' ] > 0) {
            $userIds             = MallOrder::where([['u_collage_id', '=', $row[ 'collage_id' ]], ['order_status', 'in', '10,30,50,60']])->column('user_id');
            $row[ 'order_user' ] = MallUser::where([['id', 'in', $userIds]])->select()->toArray();
        }
        $row[ 'user_order_num' ]  = MallOrder::where([['u_collage_id', '=', $row[ 'collage_id' ]], ['order_status', 'in', '10,30,50,60'], ['uid', '=', $row[ 'user_id' ]]])->count();
        $row[ 'user_order_user' ] = [];
        if ($row[ 'user_order_num' ] > 0) {
            $userIds                  = MallOrder::where([['u_collage_id', '=', $row[ 'collage_id' ]], ['order_status', 'in', '10,30,50,60'], ['uid', '=', $row[ 'user_id' ]]])->column('user_id');
            $row[ 'user_order_user' ] = MallUser::where([['id', 'in', $userIds]])->select()->toArray();
        }
        $row[ 'total_price' ]     = getPrice($row[ 'total_price' ]);
        $row[ 'order_price' ]     = getPrice($row[ 'order_price' ]);
        $row[ 'pay_price' ]       = getPrice($row[ 'pay_price' ]);
        $row[ 'pay_balance' ]     = getPrice($row[ 'pay_balance' ]);
        $row[ 'failure_subsidy' ] = getPrice($row[ 'failure_subsidy' ]);
        $this->assign('row', $row) ?? 0;
        return $this->fetch();
    }
    
    /**
     * @NodeAnotation(title="退款")
     */
    public function refund($id)
    {
        $this->checkPostRequest();
        $row = $this->model->whereIn('id', $id)->find();
        if ( !in_array($row->order_status, [30, 40, 70]) || $row->refund_status != 10) {
            $this->error('订单状态异常，请刷新重试');
        }
        $row->isEmpty() && $this->error('数据不存在');
        $balance        = MallUser::where('id', $row->user_id)->value('balance');
        $failure_reward = MallGoods::where('id', $row->goods_id)->value('failure_reward');
        try {
            //开启事务
            Db::startTrans();
            $collage = MallCollage::where('collage_id', $row->collage_id)->find();

            //处理成团奖励退回
            if ($row->receipt_time > 0) {
                MallOrder::resolveRefundSuccessReward($row->toArray());
            }
            //拼团失败
            MallOrder::resolveCollage($row->toArray());
            $modOrder = ['refund_status' => 40, 'order_status' => 70, 'collage_status' => 4, 'refund_time' => time()];
            if ($row->pay_price > 0) {
                $res = AllInPay::orderRefundInfo($row);
                if ($res[ 'trxstatus' ] == '0000') {
                    AllInPay::afterRefund($row->toArray());
                } else {
                    _throwNewException($res[ 'errmsg' ]);
                }
            } else {
                $type = 11;
                if ($row->order_status == 40) {
                    $type = 13;
                }
                $surBalance                  = $balance + $row->pay_balance;
                //加上余额
                if (false === MallUser::where([['id', '=', $row->user_id]])->update(['balance' => $surBalance])) {
                    _throwNewException('退款失败');
                }
                //添加交易记录
                $tradeLogData = [
                    'trade_type'  => $type,
                    'amount'      => $row->pay_balance,
                    'balance'     => $surBalance,
                    'order_id'    => $row->id,
                    'user_id'     => $row->user_id,
                    'create_time' => time(),
                    'update_time' => time(),
                ];
                if (false === MallTradeRecordLog::insert($tradeLogData)) {
                    _throwNewException('退款失败');
                }
                //如果拼团未成功
                if (empty($collage->finish_time)) {
                    //添加失败奖励
                    MallOrder::resolveFailureReward($failure_reward, $row->user_id, $row->id, $row->collage_id);
                    if (false === MallCollage::where('collage_id', $row->collage_id)->update(['fail_time' => time()])) {
                        _throwNewException('订单支付失败');
                    }
                }
            }
            $save = $row->save($modOrder);
            
            
            // 提交事务
            Db::commit();
            
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        $save ? $this->success('退款成功') : $this->error('退款失败');
    }
}